package com.aosan.website.common.security.config

import com.aosan.website.common.security.converter.PrincipalAuthenticationConverter
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter
import org.springframework.security.oauth2.provider.token.RemoteTokenServices

@Configuration
class ResourceConfiguration(
        private val remoteTokenServices: RemoteTokenServices
) : ResourceServerConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and().cors()
                .and()
                .csrf().disable()
    }

    override fun configure(resources: ResourceServerSecurityConfigurer) {
        super.configure(resources)
        val userAuthenticationConverter = PrincipalAuthenticationConverter()
        val accessTokenConverter = DefaultAccessTokenConverter().apply {
            setUserTokenConverter(userAuthenticationConverter)
        }
        remoteTokenServices!!.setAccessTokenConverter(accessTokenConverter)
        resources.apply {
            tokenServices(remoteTokenServices)
            resourceId("home")
        }
    }

}